package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.NewsCategoryMapper;
import com.mars.module.admin.mapper.NewsMapper;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.UserFollowRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.UserFollowMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.UserFollow;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.IUserFollowService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户关注业务层处理
 *
 * @author mars
 * @date 2024-03-04
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserFollowServiceImpl implements IUserFollowService {

    private final UserFollowMapper baseMapper;
    private final NewsMapper newsMapper;
    private final SysUserMapper userMapper;
    private final NewsCategoryMapper categoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserFollow add(UserFollowRequest request) {
        UserFollow entity = UserFollow.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setUserId(userId);
        entity.setCreateById(userId);
        Long count = baseMapper.selectCount(new QueryWrapper<UserFollow>().eq("user_id", userId)
                .eq("follower_id", request.getFollowerId()).eq("type", request.getType()));
        if (count == 0L) {
            baseMapper.insert(entity);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(UserFollowRequest request) {
        UserFollow entity = UserFollow.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public UserFollow getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<UserFollow> pageList(UserFollowRequest request) {
        Page<UserFollow> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<UserFollow> query = this.buildWrapper(request);
        IPage<UserFollow> pageRecord = baseMapper.selectPage(page, query);
        List<UserFollow> records = pageRecord.getRecords();
        List<UserFollow> recordsNew = new ArrayList<>();
        for (UserFollow follow : records) {
            SysUser sysUser = userMapper.selectById(follow.getUserId());
            if ("1".equals(follow.getType())) {
                follow.setType("文章");
                News news = newsMapper.selectById(follow.getFollowerId());
                follow.setFollowerName(news == null ? "" : news.getTitle());
            } else if ("2".equals(follow.getType())) {
                follow.setType("文章分类");
                NewsCategory category = categoryMapper.selectById(follow.getFollowerId());
                follow.setFollowerName(category == null ? "" : category.getCategoryName());
            }
            follow.setUserName(sysUser == null ? "" : sysUser.getUserName());
            recordsNew.add(follow);
        }
        if (StringUtils.isNotBlank(request.getFollowerName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getFollowerName().contains(request.getFollowerName())).collect(Collectors.toList());
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<UserFollow> list(UserFollowRequest request) {
        LambdaQueryWrapper<UserFollow> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public void remove(String followerId, String userId, String type) {
        baseMapper.delete(new QueryWrapper<UserFollow>().eq("follower_id", followerId)
                .eq("user_id", userId).eq("type", type));
    }

    private LambdaQueryWrapper<UserFollow> buildWrapper(UserFollowRequest param) {
        LambdaQueryWrapper<UserFollow> query = new LambdaQueryWrapper<>();
        return query;
    }

}
